package hk.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController @RequestMapping("/user")
public class UserController {
	@GetMapping("/test")
	public String test() {
		return "test方法调用了";
	}
	
	//这个方法用理演示如何获取 authentication 对象
	@GetMapping("/test1")
	public Authentication test1() {
		SecurityContext context = SecurityContextHolder.getContext();
		Authentication authentication = context.getAuthentication();
	  //authentication.getPrincipal() 就可以得到那个User对象	
		return authentication;
	}
	
	
	//这个方法也是用来演示如何得到 authentication对象
	@GetMapping("/test2")
	public Authentication test2(Authentication authentication) {
		System.out.println(authentication.getPrincipal());  //得到的是里面的那个 User
		return authentication;
	}
	
	@RequestMapping("create-user")
	//只有ADMIN这个角色,才可以访问,注意,数据库里要存 ADMIN,而不是 ROLE_ADMIN
	@Secured("ROLE_ADMIN")
	public String addUser() {
		return "创建用户成功";
	}
	
	@PreAuthorize("hasAuthority('user:delete')")
	@RequestMapping("delete-user")
	public String delUser() {
		return "删除用户成功";	
	}
}
